<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue';
import { marked, Renderer } from 'marked';
import mermaid from 'mermaid';
import { FileSystemUtils } from './fileSystem';
import type { FileNode, AppState } from './types';
import type { FileSystemDirectoryHandle } from './fileSystem';
import FileTreeItem from './components/FileTreeItem.vue';
import SettingsDialog from './components/SettingsDialog.vue';

// 初始化mermaid
const initializeMermaid = () => {
  try {
    mermaid.initialize({
      startOnLoad: false,
      theme: 'default',
      themeVariables: {
        primaryColor: '#42b983',
        primaryTextColor: '#fff',
        primaryBorderColor: '#42b983',
        lineColor: '#333',
        secondaryColor: '#e0e0e0',
        tertiaryColor: '#f5f5f5'
      },
      flowchart: {
        useMaxWidth: false,
        htmlLabels: true
      },
      sequence: {
        useMaxWidth: false,
        noteFontWeight: 'normal',
        noteFontSize: 14
      }
    });
  } catch (error) {
    console.error('初始化mermaid失败:', error);
  }
};

// 渲染mermaid图表
const renderMermaidCharts = () => {
  try {
    mermaid.run();
  } catch (error) {
    console.error('渲染mermaid图表失败:', error);
  }
};

// 全局函数，用于处理图片加载失败
(window as any).handleImageError = function(imageElement: HTMLImageElement) {
  // 保存原始URL，在设置错误图片之前
  const originalUrl = imageElement.src;
  console.error('图片加载失败:', originalUrl);
  
  // 设置默认的错误图片
  imageElement.src = 'data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22200%22 height=%22100%22 viewBox=%220 0 200 100%22%3E%3Crect width=%22200%22 height=%22100%22 fill=%22%23f0f0f0%22/%3E%3Ctext x=%22100%22 y=%2250%22 font-family=%22Arial%22 font-size=%2214%22 text-anchor=%22middle%22 dominant-baseline=%22middle%22 fill=%22%23666%22%3E图片加载失败%3C/text%3E%3C/svg%3E';
  imageElement.onerror = null;
  
  // 添加URL显示和复制功能
  const urlDiv = document.createElement('div');
  urlDiv.className = 'image-url';
  urlDiv.style.cssText = 'background: #f5f5f5; padding: 8px; margin-top: 8px; border-radius: 4px; font-family: monospace; word-break: break-all; max-width: 90%; margin-left: auto; margin-right: auto;';
  
  // 创建复制按钮
  const copyButton = document.createElement('button');
  copyButton.textContent = '复制';
  copyButton.style.cssText = 'margin-left: 8px; padding: 2px 8px; background: #42b983; color: white; border: none; border-radius: 3px; cursor: pointer; font-size: 12px;';
  copyButton.onclick = function() {
    const button = this as HTMLButtonElement;
    navigator.clipboard.writeText(originalUrl).then(() => {
      button.textContent = '已复制!';
      setTimeout(() => {
        button.textContent = '复制';
      }, 2000);
    });
  };
  
  // 创建访问超链接
  const visitLink = document.createElement('a');
  visitLink.textContent = '访问';
  visitLink.href = originalUrl;
  visitLink.target = '_blank';
  visitLink.rel = 'noopener noreferrer';
  visitLink.style.cssText = 'margin-left: 8px; padding: 2px 8px; background: #2196f3; color: white; border: none; border-radius: 3px; cursor: pointer; font-size: 12px; text-decoration: none;';
  
  // 组合元素 - 使用原始URL而不是错误图片URL
  urlDiv.innerHTML = '<strong>图片URL:</strong> ' + originalUrl;
  urlDiv.appendChild(copyButton);
  urlDiv.appendChild(visitLink);
  
  // 添加到父容器
  imageElement.parentNode?.appendChild(urlDiv);
};

// 转义HTML特殊字符，确保XML等代码能够正确显示
const escapeHtml = (unsafe: string): string => {
  return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
};

// 创建自定义渲染器，用于给代码块添加复制按钮和支持mermaid
const createCustomRenderer = () => {
  const renderer = new Renderer();
  
  // 覆盖图片渲染方法，确保正确处理外部图片URL
  renderer.image = function({ href, title, text }) {
    // 清理URL，移除所有反引号并修剪空白字符
    let cleanUrl = href.replace(/`/g, '').trim();
    
    // 检查URL格式，确保有http或https前缀
    if (!cleanUrl.match(/^https?:\/\//i)) {
      cleanUrl = 'https://' + cleanUrl;
    }
    
    // 构建图片标签容器，使用简单的事件处理
    let imgContainer = `
      <div class="image-container" style="text-align: center; margin: 1rem 0;">
        <img 
          src="${cleanUrl}" 
          alt="${text || '图片'}" 
          class="markdown-image" 
          style="max-width: 100%; height: auto; display: block; margin: 0 auto;"
          onload="console.log('图片加载成功:', this.src)"
          onerror="handleImageError(this)"
    `;
    
    // 如果有title属性，添加到标签中
    if (title) {
      imgContainer += ` title="${title}"`;
    }
    
    // 闭合图片标签和容器
    imgContainer += `>
      `;
    
    // 添加图片描述（如果有）
    if (text) {
      imgContainer += `<div class="image-caption" style="text-align: center; color: #666; font-size: 0.9em; margin-top: 0.5rem;">${text}</div>`;
    }
    
    imgContainer += `</div>`;
    
    return imgContainer;
  };
  
  // 覆盖代码渲染方法 - 不依赖原始的code方法
  renderer.code = function({ text, lang }: { text: string, lang?: string }) {
    const codeId = `code-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
    const escapedText = escapeHtml(text);
    
    // 处理mermaid代码块
    if (lang && (lang.toLowerCase() === 'mermaid' || lang.toLowerCase() === 'flow' || lang.toLowerCase() === 'sequence' || lang.toLowerCase() === 'class')) {
      return `
        <div class="code-block-container">
          <div class="code-block-header">
            <span class="code-language">${lang}</span>
            <button class="copy-button" data-code-id="${codeId}" title="复制代码">复制</button>
          </div>
          <pre id="${codeId}" style="display: none;"><code class="language-${lang}">${escapedText}</code></pre>
          <div class="mermaid-container">
            <div class="mermaid">${text}</div>
          </div>
        </div>
      `;
    }
    
    // 处理普通代码块
    const languageClass = lang ? `language-${lang}` : '';
    
    return `
      <div class="code-block-container">
        <div class="code-block-header">
          <span class="code-language">${lang || 'code'}</span>
          <button class="copy-button" data-code-id="${codeId}" title="复制代码">复制</button>
        </div>
        <pre id="${codeId}"><code class="${languageClass}">${escapedText}</code></pre>
      </div>
    `;
  };
  
  return renderer;
};

// 初始化自定义渲染器
const customRenderer = createCustomRenderer();
marked.use({ renderer: customRenderer });

// 添加复制功能
const setupCopyFunctionality = () => {
  // 使用事件委托处理复制按钮点击
  document.addEventListener('click', (e) => {
    const target = e.target as HTMLElement;
    if (target.classList.contains('copy-button')) {
      const codeId = target.getAttribute('data-code-id');
      if (codeId) {
        const codeElement = document.getElementById(codeId);
        if (codeElement) {
          // 对于mermaid代码块，我们从隐藏的pre标签中获取原始内容
          // 对于普通代码块，我们也从pre标签中获取，但需要注意HTML转义
          let codeContent = codeElement.textContent || '';
          
          // 尝试反转义HTML特殊字符，确保复制的是原始内容
          const unescapeHtml = (escaped: string): string => {
            return escaped
              .replace(/&amp;/g, "&")
              .replace(/&lt;/g, "<")
              .replace(/&gt;/g, ">")
              .replace(/&quot;/g, '"')
              .replace(/&#039;/g, "'");
          };
          
          codeContent = unescapeHtml(codeContent);
          
          navigator.clipboard.writeText(codeContent).then(() => {
            // 显示复制成功的提示
            const originalText = target.textContent;
            target.textContent = '已复制';
            target.classList.add('copied');
            
            setTimeout(() => {
              target.textContent = originalText;
              target.classList.remove('copied');
            }, 2000);
          }).catch(err => {
            console.error('复制失败:', err);
          });
        }
      }
    }
  });
};

// 状态管理
const state = ref<AppState>({
  fileTree: [],
  currentFile: undefined,
  searchQuery: '',
  filteredFiles: [],
  settings: { 
    markdownFolderPath: '',
    fontFamily: 'system-ui',
    fontSize: 16,
    theme: 'light'
  }
});

// 组件状态
const showSettingsDialog = ref(false);
const markdownContent = ref('');
const rootDirectoryHandle = ref<FileSystemDirectoryHandle | null>(null);

// 搜索相关状态
const isSearching = ref(false);
const searchResults = ref<FileNode[]>([]);
const showOriginalTree = ref(true);

// 展开的目录ID集合
const expandedDirectories = ref<Set<string>>(new Set());

// 计算属性：根据搜索条件过滤文件
const filteredFileTree = computed(() => {
  if (!state.value.searchQuery.trim()) {
    return state.value.fileTree;
  }

  const query = state.value.searchQuery.toLowerCase();
  
  // 过滤文件树，搜索时忽略文件夹，只显示md文件，但保留文件的父目录结构
  const filterTree = (nodes: FileNode[]): FileNode[] => {
    return nodes
      .map(node => {
        if (node.isDirectory && node.children) {
          const filteredChildren = filterTree(node.children);
          // 只保留包含匹配md文件的目录（忽略目录名称匹配）
          if (filteredChildren.length > 0) {
            return { ...node, children: filteredChildren };
          }
        } else if (!node.isDirectory && 
                   node.name.toLowerCase().includes(query) && 
                   node.name.toLowerCase().endsWith('.md')) {
          // 只显示名称匹配搜索查询的md文件
          return node;
        }
        return null;
      })
      .filter((node): node is FileNode => node !== null);
  };

  return filterTree(state.value.fileTree);
});

// 加载设置并初始化
const initializeApp = async () => {
  const savedSettings = FileSystemUtils.loadSettings();
  // 如果有保存的设置，使用保存的设置；否则使用默认设置
  state.value.settings = {
    ...state.value.settings,
    ...savedSettings
  };
  
  // 应用设置
  applySettings();
};

// 应用设置
const applySettings = () => {
  const { fontFamily, fontSize, theme } = state.value.settings;
  
  // 应用字体和字体大小到markdown内容区域
  const markdownContentEl = document.querySelector('.markdown-content') as HTMLElement | null;
  if (markdownContentEl) {
    markdownContentEl.style.fontFamily = fontFamily;
    markdownContentEl.style.fontSize = `${fontSize}px`;
  }
  
  // 应用字体到左侧导航栏相关元素
  const leftNavElements = document.querySelectorAll(
    '.file-explorer, .file-tree, .file-tree-item, .item-name, .search-container, .search-input, .search-results, .app-header h1'
  );
  
  leftNavElements.forEach(el => {
    (el as HTMLElement).style.fontFamily = fontFamily;
  });
  
  // 应用主题
  document.documentElement.classList.toggle('dark-theme', theme === 'dark');
  document.body.classList.toggle('dark-theme', theme === 'dark');
};

// 选择并加载Markdown文件夹 - 已通过设置对话框实现

// 打开Markdown文件
const openMarkdownFile = async (file: FileNode) => {
  if (file.isDirectory || !file.path) return;
  
  state.value.currentFile = file.path;
  
  // 保存最后打开的文件路径
  const savedSettings = FileSystemUtils.loadSettings();
  FileSystemUtils.saveSettings({
    markdownFolderPath: savedSettings.markdownFolderPath,
    lastOpenedFile: file.path
  });
  
  try {
    // 由于安全限制，我们需要重新获取文件句柄
    // 在实际应用中，我们应该保存根目录句柄并从中查找文件
    const fileContent = await fetchFileContent(file.path);
    markdownContent.value = fileContent;
    
    // 等待DOM更新后渲染mermaid图表
    await nextTick();
    renderMermaidCharts();
  } catch (error) {
    console.error('打开文件出错:', error);
  }
};

// 获取文件内容
const fetchFileContent = async (filePath: string): Promise<string> => {
  try {
    // 在实际的浏览器环境中，我们从已保存的根目录句柄中查找文件
    if (rootDirectoryHandle.value) {
      // 从文件路径中提取相对路径（去掉根目录名称）
      const pathParts = filePath.split('/').filter(part => part);
      const relativePath = pathParts.slice(1).join('/'); // 去掉第一个部分（根目录名称）
      
      // 查找文件句柄
      const fileHandle = await FileSystemUtils.findFileHandleByPath(rootDirectoryHandle.value, relativePath);
      if (fileHandle) {
        // 读取文件内容
        return await FileSystemUtils.readMarkdownFile(fileHandle);
      }
    }
    
    // 如果无法获取真实内容，返回模拟内容
    return `# ${filePath.split('/').pop()}\n\n这是一个Markdown文件的示例内容。\n\n## 章节1\n- 项目1\n- 项目2\n\n## 章节2\n\`\`\`javascript\nconsole.log('Hello, Markdown!');\n\`\`\``;
  } catch (error) {
    console.error('获取文件内容出错:', error);
    return `# 无法加载文件\n\n无法读取文件内容: ${filePath}\n\n错误信息: ${error instanceof Error ? error.message : '未知错误'}`;
  }
};

// 切换目录展开/折叠
const toggleDirectory = (node: FileNode) => {
  if (node.isDirectory) {
    // 切换目录的展开状态
    if (expandedDirectories.value.has(node.id)) {
      expandedDirectories.value.delete(node.id);
    } else {
      expandedDirectories.value.add(node.id);
    }
  }
};

// 处理搜索输入
const handleSearchInput = (e: Event) => {
  const target = e.target as HTMLInputElement;
  state.value.searchQuery = target.value;
  
  if (target.value.trim()) {
    isSearching.value = true;
    showOriginalTree.value = false;
    // 获取匹配的md文件克隆体
    searchResults.value = getAllMatchingFiles(state.value.fileTree, target.value.toLowerCase());
  } else {
    isSearching.value = false;
    showOriginalTree.value = true;
    searchResults.value = [];
  }
};

// 清空搜索框
const clearSearch = () => {
  state.value.searchQuery = '';
  isSearching.value = false;
  showOriginalTree.value = true;
  searchResults.value = [];
};

// 更新设置
const updateSettings = (newSettings: typeof state.value.settings) => {
  state.value.settings = newSettings;
  // 应用新的设置
  applySettings();
};

// 处理从设置对话框中选择的文件夹
const handleFolderSelected = async (data: {fileTree: FileNode[], rootHandle: FileSystemDirectoryHandle | null}) => {
  state.value.fileTree = data.fileTree;
  rootDirectoryHandle.value = data.rootHandle;
  
  // 如果有根目录句柄，保存文件夹名称作为路径标识
  if (rootDirectoryHandle.value) {
    FileSystemUtils.saveSettings({ markdownFolderPath: rootDirectoryHandle.value.name });
  }
};

// 获取所有匹配的md文件（扁平化列表）
const getAllMatchingFiles = (nodes: FileNode[], query: string): FileNode[] => {
  const results: FileNode[] = [];
  
  const searchInNode = (node: FileNode) => {
    if (node.isDirectory && node.children) {
      node.children.forEach(searchInNode);
    } else if (!node.isDirectory && 
               node.name.toLowerCase().includes(query) && 
               node.name.toLowerCase().endsWith('.md')) {
      // 创建文件的克隆体，添加一个标记来区分是搜索结果
      const fileClone = { ...node, isSearchResult: true };
      results.push(fileClone);
    }
  };

  nodes.forEach(searchInNode);
  return results;
};

// 递归查找文件路径对应的所有父目录ID
// 递归查找文件路径对应的所有父目录ID
const findPathDirectoryIds = (filePath: string) => {
  // 通过遍历文件树来查找文件并收集路径上的所有目录ID
  const collectDirectoryPath = (nodes: FileNode[], targetPath: string, currentPath: string = ''): string[] => {
    for (const node of nodes) {
      const nodePath = currentPath ? `${currentPath}/${node.name}` : node.name;
      
      if (!node.isDirectory) {
        // 如果是文件且路径匹配，返回空数组表示找到了文件
        if (node.path === targetPath) {
          return [];
        }
      } else if (node.isDirectory && node.children) {
        // 如果是目录，递归检查子节点
        const childResult = collectDirectoryPath(node.children, targetPath, nodePath);
        // 如果在子节点中找到了文件，将当前目录ID添加到结果前面
        if (childResult !== null) {
          return [node.id, ...childResult];
        }
      }
    }
    // 返回null表示在此分支中未找到文件
    return [];
  };
  
  // 开始查找并返回结果
  const result = collectDirectoryPath(state.value.fileTree, filePath);
  return result || [];
};

// 从搜索结果中打开文件
const openMarkdownFileFromSearch = async (file: FileNode) => {
  // 显示原始文件树
  showOriginalTree.value = true;
  isSearching.value = false;
  
  // 选中并打开文件
  if (file.path) {
    state.value.currentFile = file.path;
    
    // 保存最后打开的文件路径
    const savedSettings = FileSystemUtils.loadSettings();
    FileSystemUtils.saveSettings({
      markdownFolderPath: savedSettings.markdownFolderPath,
      lastOpenedFile: file.path
    });
    
    // 找到并展开所有包含该文件的目录
    const directoryIds = findPathDirectoryIds(file.path);
    
    // 清空并重新填充展开的目录集合
    expandedDirectories.value.clear();
    directoryIds.forEach(id => expandedDirectories.value.add(id));

    try {
      const fileContent = await fetchFileContent(file.path);
      markdownContent.value = fileContent;
      
      // 等待DOM更新后渲染mermaid图表
      await nextTick();
      renderMermaidCharts();
    } catch (error) {
      console.error('打开文件出错:', error);
    }
  }
};

// 生命周期钩子
  onMounted(async () => {
    initializeApp();
    setupCopyFunctionality();
    initializeMermaid();
    
    // 检查是否有已保存的文件夹路径
    const savedSettings = FileSystemUtils.loadSettings();
    if (savedSettings.markdownFolderPath) {
      // 直接加载历史文件夹，无需用户确认
      try {
        const result = await FileSystemUtils.selectFolderAndBuildTree();
        if (result.rootHandle && result.fileTree.length > 0) {
          state.value.fileTree = result.fileTree;
          rootDirectoryHandle.value = result.rootHandle;
          // 保存设置
          FileSystemUtils.saveSettings({
            markdownFolderPath: savedSettings.markdownFolderPath,
            lastOpenedFile: savedSettings.lastOpenedFile
          });
          
          // 如果有保存的最后打开文件，尝试加载它
          if (savedSettings.lastOpenedFile) {
            try {
              // 设置当前文件
              state.value.currentFile = savedSettings.lastOpenedFile;
              
              // 找到并展开所有包含该文件的目录
              const directoryIds = findPathDirectoryIds(savedSettings.lastOpenedFile);
              
              // 清空并重新填充展开的目录集合
              expandedDirectories.value.clear();
              directoryIds.forEach(id => expandedDirectories.value.add(id));
              
              // 获取文件内容
              const fileContent = await fetchFileContent(savedSettings.lastOpenedFile);
              markdownContent.value = fileContent;
              
              // 等待DOM更新后渲染mermaid图表
              await nextTick();
              renderMermaidCharts();
            } catch (error) {
              console.error('加载最后打开的文件出错:', error);
              // 出错时不影响应用继续运行
            }
          }
        }
      } catch (error) {
        console.error('加载历史文件夹出错:', error);
        // 出错时不影响应用继续运行
      }
    }
  });
</script>

<template>
  <div class="markdown-manager">
    <!-- 顶部导航栏 -->
    <header class="app-header">
      <h1>Markdown文档管理器</h1>
      <div class="header-actions">
        <button class="btn" @click="showSettingsDialog = true">设置</button>
      </div>
    </header>

    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 左侧文件树区域 -->
      <aside class="file-explorer">
        <!-- 搜索 -->
        <div class="file-explorer-header">
          <div class="search-container">
            <input
              type="text"
              placeholder="搜索Markdown文件..."
              v-model="state.searchQuery"
              class="search-input"
              @input="handleSearchInput"
            />
            <button
              v-if="state.searchQuery"
              class="clear-search-btn"
              @click="clearSearch"
              title="清空搜索"
            >
              ×
            </button>
          </div>
        </div>

        <!-- 文件树 -->
        <div class="file-tree">
          <!-- 搜索结果显示 -->
          <template v-if="isSearching && searchResults.length > 0">
            <div class="search-results-header">
              找到 {{ searchResults.length }} 个匹配的文件
            </div>
            <div class="search-results">
              <div
                v-for="result in searchResults"
                :key="result.id + '-search'"
                class="search-result-item"
                @click="openMarkdownFileFromSearch(result)"
              >
                <span class="search-result-icon">📄</span>
                <span class="search-result-name">{{ result.name }}</span>
                <span class="search-result-path">{{ result.path }}</span>
              </div>
            </div>
          </template>
          
          <!-- 原始文件树显示 -->
          <template v-else-if="showOriginalTree">
            <template v-if="filteredFileTree.length > 0">
              <FileTreeItem
                v-for="node in filteredFileTree"
                :key="node.id"
                :node="node"
                :expanded="expandedDirectories.has(node.id)"
                @click="openMarkdownFile"
                @toggle="toggleDirectory"
              />
            </template>
            <div v-else class="empty-state">
              {{ state.searchQuery ? '没有找到匹配的文件' : '请选择一个包含Markdown文件的文件夹' }}
            </div>
          </template>
          
          <!-- 搜索无结果 -->
          <template v-else-if="isSearching">
            <div class="empty-state">
              没有找到匹配的文件
            </div>
          </template>
        </div>
      </aside>

      <!-- 右侧内容显示区域 -->
      <section class="content-viewer">
        <div v-if="markdownContent" class="markdown-content" v-html="marked.parse(markdownContent)"></div>
        <div v-else class="welcome-screen">
          <h2>欢迎使用Markdown文档管理器</h2>
          <p>请从左侧选择一个Markdown文件查看内容</p>
        </div>
      </section>
    </main>

    <!-- 设置对话框 -->
    <SettingsDialog
      v-model="showSettingsDialog"
      :settings="state.settings"
      @update-settings="updateSettings"
      @folder-selected="handleFolderSelected"
    />
  </div>
</template>

<style scoped>
.markdown-manager {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 2rem;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.app-header h1 {
  margin: 0;
  font-size: 1.5rem;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 1rem;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.file-explorer {
  width: 300px;
  background-color: #fff;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.file-explorer-header {
  padding: 1rem;
  border-bottom: 1px solid #e0e0e0;
}

.search-container {
  position: relative;
  width: 100%;
}

.search-input {
  width: 100%;
  padding: 0.5rem 2rem 0.5rem 0.5rem;
  margin-top: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.9rem;
}

.clear-search-btn {
  position: absolute;
  right: 0.5rem;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #666;
  font-size: 1.2rem;
  cursor: pointer;
  padding: 0;
  width: 1.2rem;
  height: 1.2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s;
}

.clear-search-btn:hover {
  background-color: #f0f0f0;
  color: #333;
}

.file-tree {
  flex: 1;
  overflow-y: auto;
  padding: 0.5rem;
}

.empty-state {
  padding: 2rem;
  text-align: center;
  color: #666;
  font-style: italic;
}

.content-viewer {
  flex: 1;
  overflow-y: auto;
  padding: 2rem;
  background-color: #fff;
}

.markdown-content {
  max-width: 800px;
  margin: 0 auto;
}

.welcome-screen {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #666;
}

/* 搜索结果样式 */
.search-results-header {
  padding: 0.5rem 0;
  margin-bottom: 0.5rem;
  font-weight: 600;
  color: #666;
  border-bottom: 1px solid #eee;
}

.search-results {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.search-result-item {
  display: flex;
  align-items: center;
  padding: 0.5rem;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.search-result-item:hover {
  background-color: #f0f0f0;
}

.search-result-icon {
  margin-right: 0.5rem;
  font-size: 1rem;
}

.search-result-name {
  flex: 1;
  font-weight: 500;
  color: #333;
}

.search-result-path {
  font-size: 0.8rem;
  color: #666;
  margin-left: 0.5rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 40%;
}

/* 按钮样式 */
.btn {
  padding: 0.5rem 1rem;
  border: 1px solid #ddd;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.3s;
}

.btn:hover {
  background-color: #f0f0f0;
}

.btn.primary {
  background-color: #42b983;
  color: white;
  border-color: #42b983;
}

.btn.primary:hover {
  background-color: #3aa876;
}

/* 深色主题下的组件样式 */
.dark-theme .markdown-manager {
  background-color: #121212;
}

.dark-theme .app-header {
  background-color: #1e1e1e;
  border-bottom-color: #333;
}

.dark-theme .app-header h1 {
  color: #ffffff;
}

.dark-theme .header-actions {
  color: #d4d4d4;
}

.dark-theme .file-explorer {
  background-color: #1e1e1e;
  border-right-color: #333;
}

.dark-theme .file-explorer-header {
  border-bottom-color: #333;
}

.dark-theme .search-input {
  background-color: #2d2d2d;
  border-color: #444;
  color: #d4d4d4;
}

.dark-theme .search-input:focus {
  border-color: #42b983;
}

.dark-theme .clear-search-btn {
  color: #999;
}

.dark-theme .clear-search-btn:hover {
  background-color: #333;
  color: #d4d4d4;
}

.dark-theme .file-tree {
  color: #d4d4d4;
}

.dark-theme .file-tree-item {
  color: #d4d4d4;
}

.dark-theme .file-tree-item:hover {
  background-color: #2d2d2d;
}

.dark-theme .file-tree-item.folder {
  color: #42b983;
}

.dark-theme .file-tree-item.file {
  color: #d4d4d4;
}

.dark-theme .empty-state {
  color: #999;
}

.dark-theme .content-viewer {
  background-color: #121212;
}

.dark-theme .welcome-screen {
  color: #999;
}

.dark-theme .search-results-header {
  color: #999;
  border-bottom-color: #333;
}

.dark-theme .search-results {
  color: #d4d4d4;
}

.dark-theme .search-result-item:hover {
  background-color: #2d2d2d;
}

.dark-theme .search-result-icon {
  color: #d4d4d4;
}

.dark-theme .search-result-name {
  color: #ffffff;
}

.dark-theme .search-result-path {
  color: #b0b0b0;
}

.dark-theme .btn {
  background-color: #1e1e1e;
  border-color: #444;
  color: #d4d4d4;
}

.dark-theme .btn:hover {
  background-color: #2d2d2d;
  border-color: #555;
}

.dark-theme .btn:active {
  background-color: #333;
}

.dark-theme .btn.primary {
  background-color: #42b983;
  border-color: #42b983;
  color: white;
}

.dark-theme .btn.primary:hover {
  background-color: #3aa876;
  border-color: #3aa876;
}

.dark-theme .btn.primary:active {
  background-color: #369c70;
}
</style>

<style>
/* 代码块容器样式 */
.code-block-container {
  position: relative;
  margin-bottom: 1.5rem;
  border-radius: 4px;
  overflow: hidden;
}

/* 代码块头部样式 */
.code-block-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 1rem;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
  font-size: 0.85rem;
}

/* 代码语言标签样式 */
.code-language {
  color: #666;
  font-weight: 500;
}

/* 复制按钮样式 */
.copy-button {
  padding: 0.25rem 0.75rem;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 3px;
  font-size: 0.85rem;
  cursor: pointer;
  transition: all 0.2s;
}

.copy-button:hover {
  background-color: #42b983;
  color: white;
  border-color: #42b983;
}

.copy-button.copied {
  background-color: #28a745;
  border-color: #28a745;
  color: white;
}

/* 代码块样式 */
.code-block-container pre {
  margin: 0;
  padding: 1rem;
  background-color: #f8f8f8;
  border-radius: 0 0 4px 4px;
  overflow-x: auto;
}

.code-block-container code {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 0.9rem;
}

/* 深色主题下的代码块样式 */
.dark-theme .code-block-header {
  background-color: #2d2d2d;
  border-bottom-color: #444;
}

.dark-theme .code-language {
  color: #999;
}

.dark-theme .copy-button {
  background-color: #1e1e1e;
  border-color: #444;
  color: #d4d4d4;
}

.dark-theme .copy-button:hover {
  background-color: #42b983;
  border-color: #42b983;
  color: white;
}

.dark-theme .copy-button.copied {
  background-color: #28a745;
  border-color: #28a745;
}

.dark-theme .code-block-container pre {
  background-color: #1e1e1e;
}

/* mermaid图表容器样式 */
.mermaid-container {
  padding: 1rem;
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-top: none;
  border-radius: 0 0 4px 4px;
  overflow-x: auto;
}

/* 深色主题下的mermaid图表样式 */
.dark-theme .mermaid-container {
  background-color: #1e1e1e;
  border-color: #444;
}

/* mermaid图表字体大小 */
.mermaid {
  font-size: 14px;
  line-height: 1.4;
}

/* 确保mermaid图表不溢出容器 */
.mermaid svg {
  max-width: 100%;
  height: auto;
}

/* 深色主题下的mermaid图表颜色 */
.dark-theme .mermaid rect, .dark-theme .mermaid path, .dark-theme .mermaid line {
  stroke: #d4d4d4;
}

.dark-theme .mermaid text {
  fill: #d4d4d4;
}

.dark-theme .mermaid .node rect, .dark-theme .mermaid .node circle, .dark-theme .mermaid .node ellipse {
  fill: #2d2d2d;
  stroke: #42b983;
}
</style>
